package com.mjk.common.core.jdbc.service.parse.type.impl.sql.type.impl;


import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.core.jdbc.service.parse.type.impl.sql.type.IBeeSqlPrase;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * if标签解析
 * @author Administrator
 *
 */
public class BeeSqlChoosePrase implements IBeeSqlPrase {

    /**
     * 解析choose SQL 语句
     * @param sql
     * @return
     */
    public  String praseSql(String sql,Map<String,Object> params ) {
    	Pattern choosePattern = Pattern.compile(BeeCommonConstns.CHOOSEREGEX, Pattern.DOTALL);
        Pattern whenPattern = Pattern.compile(BeeCommonConstns.WHENREGEX, Pattern.DOTALL);
        Pattern otherwisePattern = Pattern.compile(BeeCommonConstns.OTHERWISEREGEX, Pattern.DOTALL);
        Matcher matcher = choosePattern.matcher(sql);
        StringBuffer sb = new StringBuffer();

        while (matcher.find()) {
            String chooseContent = matcher.group(1);
            Matcher whenMatcher = whenPattern.matcher(chooseContent);
            StringBuilder csb = new StringBuilder();
            while (whenMatcher.find()) {
            	String test = whenMatcher.group("test");
            	if(isMatch(test,params)) {
            		csb.append(whenMatcher.group("content"));
            	}
            }
            Matcher otherwiseMatcher = otherwisePattern.matcher(chooseContent);
            String otherwiseContent = "";
            if (otherwiseMatcher.find()) {
                otherwiseContent = otherwiseMatcher.group("content").trim();
            }
            if(csb.length()<=0) {
            	csb.append(otherwiseContent);
            }
            matcher.appendReplacement(sb, csb.toString());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
